package com.cty.util.util;

import org.slf4j.MDC;

import java.util.Random;
import java.util.UUID;

/**
 * 日志链路工具类
 *
 * @author : cty
 * @since 2023/11/19
 */

public class MDCUtils {
    private MDCUtils() {
    }

    /**
     * 日志traceId
     */
    private static final String TRACE_ID = "TRACE_ID";
    private static final String EMPTY = "";

    /**
     * 随机数
     */
    private static final Random RANDOM = new Random();


    /**
     * 获取日志traceId
     */
    public static String getLogId() {
        return MDC.get(TRACE_ID);
    }

    /**
     * 移除日志traceId
     */
    public static void clear() {
        MDC.remove(TRACE_ID);
        //Thread.currentThread().setName(EMPTY);
    }

    /**
     * 新建日志traceId
     */
    public static void newLogId() {
        newLogId(getNewLogId());
    }


    /**
     * 新建日志traceId
     */
    private static void newLogId(String traceId) {
        MDC.put(TRACE_ID, traceId);
        //traceId = traceId == null ? EMPTY : traceId;
        //Thread.currentThread().setName(traceId);
    }

    /**
     * 生成新的日志ID
     *
     * @return 新ID
     */
    private static String getNewLogId() {
        return new UUID(RANDOM.nextLong(), RANDOM.nextLong()).toString().replace("-", "");
    }
}
